package org.example.javax.crypto;

import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class SHA1Encode {
  public static String CHARSET = "UTF-8";
  private static Logger logger = Logger.getLogger(SHA1Encode.class);


  /**
   * SHA1编码
   *
   * @param in 待编码值
   * @return 已编码值
   */
  public static String sha1Encode(String in) {
    StringBuilder buf = new StringBuilder();
    try {
      MessageDigest messagedigest = MessageDigest.getInstance("SHA-1");
      messagedigest.update(in.getBytes(CHARSET));
      byte[] out = messagedigest.digest();
      for (int a : out) {
        if (a < 0)
          a += 256;
        if (a < 16)
          buf.append("0");
        buf.append(Integer.toHexString(a));
      }
    } catch (NoSuchAlgorithmException e) {
      logger.error("SHA1编码出错！", e);
    } catch (UnsupportedEncodingException e) {
      logger.error("SHA1编码操作，不支持字符集" + CHARSET + "！");
    }
    return buf.toString();
  }

  public static void main(String[] args) {
    System.out.println(SHA1Encode.sha1Encode("87有为青年"));
  }
}
